package com.ww.disruptor.producer;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;
import com.ww.disruptor.event.Trade;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * 说明
 * =====================
 * 创建生产者
 * =====================
 * 模拟线程池来提交消息。
 * 需要实现Runnable接口，在之前的快速开始中我们使用RingBuffer来发布消息，
 * 在这里直接使用Disruptor对象来发布消息，只是通过Disruptor发布消息需要一个实现EventTranslator接口的对象。
 *
 * 这种方式相比之前通过RingBuffer的方式要简单一点，不需要拿到Sequence
 *
 * @author wanggw
 * @date 2024-09-14 23:33:02
 */
public class TradePublisher implements Runnable {

    private Disruptor<Trade> disruptor;

    private CountDownLatch latch;

    private static int PUBLIC_COUNT = 1;

    public TradePublisher(CountDownLatch latch, Disruptor<Trade> disruptor) {
        this.latch = latch;
        this.disruptor = disruptor;
    }

    @Override
    public void run() {
        for (int i = 0; i < PUBLIC_COUNT; i++) {
            // 新提交任务
            disruptor.publishEvent(new TradeEventTranslator());
        }
        latch.countDown();
    }

    class TradeEventTranslator implements EventTranslator<Trade> {

        private Random random = new Random();

        @Override
        public void translateTo(Trade trade, long l) {
            generateTrade(trade);
        }

        private void generateTrade(Trade event) {
            event.setPrice(random.nextDouble() * 9999);
        }
    }
}
